package org.kernely.test.security;

import java.util.Set;
import java.util.TreeSet;

import org.kernely.security.dao.RoleDAO;
import org.kernely.security.persistence.Role;
import org.kernely.test.testbundle.TestBundle;
import org.kernely.ui.mvp.KernelyPresenter;
import org.kernely.ui.utils.KernelyNotification;

import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;

/**
 * The SecurityPresenter class
 */
public class SecurityPresenter extends KernelyPresenter<SecurityView>{

	/**
	 * @see org.kenely.core.service.IKernelyPresenter#bind()
	 */
	@SuppressWarnings("serial")
	@Override
	public final void bind() {
		// Fill the combo box with all available roles.
		listAllRoles();
		
		// Adding a listener to the button
		this.view.getAddRoleButton().addListener(new ClickListener(){
			/**
			 * Called when a ClickEvent is fired
			 */
			public void buttonClick (Button.ClickEvent event) {
				// Call the process to enter a new role
				newRoleProcess();
				
			}
		});

	}
	
	// Fill the combobox with existing roles
	private void listAllRoles(){
		this.view.getRolesBox().removeAllItems();
		Set<Role> allRoles = RoleDAO.getInstance().getAllRoles();
		TreeSet<Role> sorted = new TreeSet<Role>(allRoles);
		for (Role role : sorted){
			this.view.getRolesBox().addItem(role.getName());
		}
		// Select the first item
		this.view.getRolesBox().setValue(0);
	}
	
	// Sample to see how to register a role in the application
	private void newRoleProcess(){
		try {
			// First, we verify the validity of input
			this.view.getRoleField().validate();

			// Call the service to add the role.
			String roleName = this.view.getRoleField().getValue().toString();
			TestBundle.getSecurityService().registerNewRole(roleName);
			
			// Then we refresh the combo box.
			listAllRoles();

			// Log the success on screen.
			this.view.getWindow().showNotification(new KernelyNotification("The role "+roleName+" is registered.", KernelyNotification.INFO_ICON));
			
		} catch (InvalidValueException e){
			// Log the failure on screen, to give feedback to the user
			this.view.getWindow().showNotification(new KernelyNotification("You must enter a name for the role.", KernelyNotification.WARNING_ICON));
		}
		
	}
}
